const express = require("express");
const mysql = require("mysql2/promise");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(cors());
const db = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "",
  database: "interview",
});
app.get("/categories", async (req, res) => {
  try {
    const [rows] = await db.query("SELECT * FROM categories");
    res.json(rows);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.post("/categories", async (req, res) => {
  const { code, name } = req.body;
  try {
    const [result] = await db.query(
      "INSERT INTO categories (code, name) VALUES (?, ?)",
      [code, name]
    );
    res.json({
      id: result.insertId,
      code,
      name,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.put("/categories/:id", async (req, res) => {
  const { code, name } = req.body;
  const id = req.params.id;
  try {
    await db.query("UPDATE categories SET code = ?, name = ? WHERE id = ?", [
      code,
      name,
      id,
    ]);
    res.json({
      id,
      code,
      name,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.delete("/categories/:id", async (req, res) => {
  const id = req.params.id;
  try {
    await db.query("DELETE FROM categories WHERE id = ?", [id]);
    res.json({
      message: "Deleted successfully",
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.get("/topics", async (req, res) => {
  const categoryId = req.query.category_id;
  const pageSize = parseInt(req.query.pageSize || 10);
  const currentPage = parseInt(req.query.currentPage || 1);

  const offset = (currentPage - 1) * pageSize;

  let query = "SELECT * FROM topics";
  let countQuery = "SELECT COUNT(*) as total FROM topics";

  const queryParams = [];
  const countParams = [];

  if (categoryId) {
    query += " WHERE category_id = ?";
    countQuery += " WHERE category_id = ?";
    queryParams.push(categoryId);
    countParams.push(categoryId);
  }

  query += " LIMIT ? OFFSET ?";
  queryParams.push(pageSize, offset);

  try {
    const [rows] = await db.query(query, queryParams);
    const [totalRows] = await db.query(countQuery, countParams);
    const totalRecords = totalRows[0].total;
    const totalPages = Math.ceil(totalRecords / pageSize);

    res.json({
      totalPages,
      list: rows,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.get("/topic/:id", async (req, res) => {
  const topicId = req.params.id;

  const query = "SELECT * FROM topics WHERE id = ?";

  try {
    const [rows] = await db.query(query, [topicId]);

    if (rows.length === 0) {
      return res.status(404).json({
        error: "Topic not found",
      });
    }

    res.json(rows[0]);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.post("/topics", async (req, res) => {
  const { category_id, question, answer } = req.body;
  try {
    const [result] = await db.query(
      "INSERT INTO topics (category_id, question, answer) VALUES (?, ?, ?)",
      [category_id, question, answer]
    );
    res.json({
      id: result.insertId,
      category_id,
      question,
      answer,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.put("/topics/:id", async (req, res) => {
  const { category_id, question, answer } = req.body;
  const id = req.params.id;
  try {
    await db.query(
      "UPDATE topics SET category_id = ?, question = ?, answer = ? WHERE id = ?",
      [category_id, question, answer, id]
    );
    res.json({
      id,
      category_id,
      question,
      answer,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.delete("/topics/:id", async (req, res) => {
  const id = req.params.id;
  try {
    await db.query("DELETE FROM topics WHERE id = ?", [id]);
    res.json({
      message: "Deleted successfully",
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});
app.listen(port, () => {
  console.log(`Server started on http://localhost:${port}`);
});
